import { reqGetHospitalSetItem } from '@/api/hospital/hospitalSet';
import { reqUpdateHospitalSet } from '@/api/hospital/hospitalSet';
import { reqAddHostpitalSet } from '@/api/hospital/hospitalSet'
import { AddHospitalSetParams } from '@/api/hospital/model/hospitalSet'
import { Button, Card, Form, Input, Space, message } from 'antd'
import { useForm } from 'antd/lib/form/Form';
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom';

export default function AddOrUpdateHospitalSet() {
  //声明一个状态
  let [loading, setLoading] = useState(false);
  //获得 navigate 函数
  let navigate = useNavigate();
  //声明 finish 函数
  let finish = async (values: AddHospitalSetParams) => {
    setLoading(true);
    try {
      if (!id) {
        //发送 AJAX 请求新增医院设置
        await reqAddHostpitalSet(values);
        //请求成功的操作
        message.success('添加成功');
      } else {
        //更新操作
        await reqUpdateHospitalSet({...values, id: +(id)});
        message.success('更新成功');
      }
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  }

  //声明 back 函数
  let back = () => {
    navigate('/syt/hospital/hostpitalSet');
  }

  //使用 useParams 获取 url 中的 id 参数
  let { id } = useParams();
  //获取 form 对象
  let [form] = useForm();

  //组件挂载完成的操作
  useEffect(() => {
    //发送 AJAX 请求获取当前 id 的数据
    let getHospital = async () => {
      //获取数据
      let result = await reqGetHospitalSetItem(id as string);
      //设置表单元素的值
      form.setFieldsValue(result);
    }
    //调用
    getHospital();
  }, [])

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onFinish={finish}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: '医院名称不能为空' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: '医院编号不能为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="API基础路径"
          name="apiUrl"
          rules={[{ required: true, message: 'API基础路径不能为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: '联系人姓名不能为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[{ required: true, message: '联系人手机不能为空' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 22 }}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              {id ? '更新' : '新增'}
            </Button>
            <Button onClick={back}>返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  )
}
